package com.swas.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swas.entity.BuyBack;
import com.swas.entity.BuyCheck;
import com.swas.service.BuyCheckService;
import com.swas.vo.BaseStockVO;
import com.swas.vo.BuyCheckVO;
import com.swas.util.ResultVO;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author lxysky
 */
@RestController
@RequestMapping("/buycheck")
public class BuyCheckController {

    @Autowired
    private BuyCheckService buyCheckService;

    @GetMapping("/searchLikeNo")
    public ResultVO searchLikeNo(@Param("name") String name, @Param("no") String no, @RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BuyCheckVO> list = buyCheckService.searchLikeNo(name, no);
        PageInfo<BuyCheckVO> pageInfo = new PageInfo<>(list);
        return ResultVO.success("查询成功", pageInfo);
    }

    @GetMapping("/searchLike")
    public ResultVO searchLike(@Param("name") String name, @Param("checkdate") String checkdate, @RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BuyCheckVO> list = buyCheckService.searchLike(name, checkdate);
        PageInfo<BuyCheckVO> pageInfo = new PageInfo<>(list);
        return ResultVO.success("查询成功", pageInfo);
    }

    @GetMapping("/selectAllNo")
    public ResultVO selectAllNo(@RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BuyCheckVO> list = buyCheckService.selectAllNo();
        PageInfo<BuyCheckVO> pageInfo = new PageInfo<>(list);
        return ResultVO.success("查询成功", pageInfo);
    }

    @GetMapping("/selectAll")
    public ResultVO selectAll(@RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BuyCheckVO> list = buyCheckService.selectAll();
        PageInfo<BuyCheckVO> pageInfo = new PageInfo<>(list);
        return ResultVO.success("查询成功", pageInfo);
    }

    @GetMapping("/updateCheck")
    public ResultVO updateCheck(@Param("id") Integer id, @Param("checkman") String checkman) {
        boolean flag = buyCheckService.updateCheck(id, checkman);
        if (flag) {
            return ResultVO.success("修改成功");
        } else {
            return ResultVO.fail("修改失败");
        }
    }

    @GetMapping("/addCheck")
    public ResultVO addCheck(@Param("buyman") String buyman, @Param("stockid") Integer stockid, @Param("usedate") String usedate, @Param("buysum") Integer buysum, @Param("buydate") Date buydate, @Param("description") String description, @Param("money") BigDecimal money, @Param("price") BigDecimal price) throws ParseException {
        BuyCheckVO buyCheckVO = new BuyCheckVO();
        buyCheckVO.setBuyman(buyman);
        buyCheckVO.setStockid(stockid);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        buyCheckVO.setUsedate(sdf.parse(usedate));
        buyCheckVO.setBuysum(buysum);
        buyCheckVO.setBuydate(buydate);
        buyCheckVO.setDescription(description);
        buyCheckVO.setMoney(money.longValue());
        boolean flag = buyCheckService.addCheck(buyCheckVO);
        if (flag) {
            return ResultVO.success("添加成功");
        } else {
            return ResultVO.fail("添加失败");
        }
    }

    @GetMapping("/selectBuyCheckAll")
    public ResultVO selectBuyCheckAll(@RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BaseStockVO> list = buyCheckService.selectBuyCheckAll();
        PageInfo<BaseStockVO> pageInfo = new PageInfo<>(list);
        return ResultVO.success("查询成功", pageInfo);
    }

    @GetMapping("/selectLike")
    public ResultVO selectLike(@Param("name")String name,@Param("buyman") String buyman, @RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<BaseStockVO> buyCheck = buyCheckService.selectLike(name,buyman);
        PageInfo<BaseStockVO> pageInfo = new PageInfo<>(buyCheck);
        return  ResultVO.success("查询成功", pageInfo);
    }

    @GetMapping("/getOne")
    public  ResultVO getOne(@Param("id") Integer id){
        BuyBack buyBack = buyCheckService.getOne(id);
        return ResultVO.success("ok", buyBack);
    }

    @GetMapping("/setOne")
    public  ResultVO setOne(@Param("id") Integer id, @Param("dec") String dec){
        boolean flag = buyCheckService.setOne(id, dec);
        if (flag){
            return ResultVO.success("ok");
        } else {
            return ResultVO.success("error");
        }
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("采购审核表");

        Row headerRow = sheet.createRow(0);
        String[] columns = {"设备型号", "设备名称", "采购数量", "采购金额", "采购人", "购买日期", "预计启用日期", "设备描述"};
        for (int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);

            CellStyle headerStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            headerStyle.setFont(font);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            cell.setCellStyle(headerStyle);
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        workbook.close();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "import_template.xlsx");

        return ResponseEntity.ok()
                .headers(headers)
                .body(out.toByteArray());
    }

    @PostMapping("/importExcel")
    public ResponseEntity<Void> importExcel(@RequestParam("file") MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                Cell noCell = row.getCell(0);
                Cell nameCell = row.getCell(1);
                Cell buysumCell = row.getCell(2);
                Cell moneyCell = row.getCell(3);
                Cell buymanCell = row.getCell(4);
                Cell buydateCell = row.getCell(5);
                Cell usedateCell = row.getCell(6);
                Cell descriptionCell = row.getCell(7);
                BuyCheckVO buyCheckVO = new BuyCheckVO();
                buyCheckVO.setNo(noCell.getStringCellValue());
                buyCheckVO.setName(nameCell.getStringCellValue());
                buyCheckVO.setBuysum((int) buysumCell.getNumericCellValue());
                buyCheckVO.setMoney((long) moneyCell.getNumericCellValue());
                buyCheckVO.setBuyman(buymanCell.getStringCellValue());
                buyCheckVO.setBuydate(buydateCell.getDateCellValue());
                buyCheckVO.setUsedate(usedateCell.getDateCellValue());
                buyCheckVO.setDescription(descriptionCell.getStringCellValue());
                buyCheckService.addCheck(buyCheckVO);
            }
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.ok().build();
    }

    @GetMapping("/exportExcel")
    public ResponseEntity<byte[]> exportExcel() throws IOException {
        List<BuyCheckVO> list = buyCheckService.selectAll();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("采购审核通过表");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("编号");
        headerRow.createCell(1).setCellValue("设备型号");
        headerRow.createCell(2).setCellValue("设备名称");
        headerRow.createCell(3).setCellValue("采购数量");
        headerRow.createCell(4).setCellValue("采购金额");
        headerRow.createCell(5).setCellValue("采购人");
        headerRow.createCell(6).setCellValue("预计启用日期");
        headerRow.createCell(7).setCellValue("设备描述");
        headerRow.createCell(8).setCellValue("审核日期");
        headerRow.createCell(9).setCellValue("审核人");

        CellStyle cellStyle = workbook.createCellStyle();
        DataFormat format = workbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("#,##0.00"));

        int rowNum = 1;
        for (BuyCheckVO buyCheckVO : list) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(buyCheckVO.getId().toString());
            row.createCell(1).setCellValue(buyCheckVO.getNo());
            row.createCell(2).setCellValue(buyCheckVO.getName());
            row.createCell(3).setCellValue(buyCheckVO.getBuysum());
            row.createCell(4).setCellValue(buyCheckVO.getMoney());
            row.createCell(5).setCellValue(buyCheckVO.getBuyman());
            Date usedate = buyCheckVO.getUsedate();
            String usedateStr = sdf.format(usedate);
            row.createCell(6).setCellValue(usedateStr);
            row.createCell(7).setCellValue(buyCheckVO.getDescription());
            Date checkdate = buyCheckVO.getCheckdate();
            String checkdateStr = sdf.format(checkdate);
            row.createCell(8).setCellValue(checkdateStr);
            row.createCell(9).setCellValue(buyCheckVO.getCheckman());
            for (int i = 1; i <= list.size(); i++) {
                cellStyle.setAlignment(HorizontalAlignment.LEFT);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                row.getCell(i).setCellStyle(cellStyle);
            }
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        byte[] bytes = byteArrayOutputStream.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=buyCheck.xlsx");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(bytes);
    }

    @GetMapping("/exportBackExcel")
    public ResponseEntity<byte[]> exportBackExcel() throws IOException {
        List<BaseStockVO> list = buyCheckService.selectBuyCheckAll();
        System.out.println(list);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("采购反馈表");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("设备型号");
        headerRow.createCell(1).setCellValue("设备名称");
        headerRow.createCell(2).setCellValue("设备描述");
        headerRow.createCell(3).setCellValue("采购时间");
        headerRow.createCell(4).setCellValue("采购数量");
        headerRow.createCell(5).setCellValue("采购金额");
        headerRow.createCell(6).setCellValue("采购人");
        headerRow.createCell(7).setCellValue("实际单价");
        headerRow.createCell(8).setCellValue("实际购买量");
        headerRow.createCell(9).setCellValue("实际花费");
        headerRow.createCell(10).setCellValue("反馈描述");
        headerRow.createCell(11).setCellValue("反馈状态");

        CellStyle cellStyle = workbook.createCellStyle();
        DataFormat format = workbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("#,##0.00"));

        int rowNum = 1;
        for (BaseStockVO baseStockVO : list) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(baseStockVO.getNo());
            row.createCell(1).setCellValue(baseStockVO.getName());
            row.createCell(2).setCellValue(baseStockVO.getDescription());
            if (baseStockVO.getBuydate() == null){
                row.createCell(3).setCellValue("");
            } else{
                row.createCell(3).setCellValue(sdf.format(baseStockVO.getBuydate()));
            }
            if (baseStockVO.getBuysum() == null){
                row.createCell(4).setCellValue("");
            } else {
                row.createCell(4).setCellValue(baseStockVO.getBuysum());
            }
            if (baseStockVO.getMoney() == null){
                row.createCell(5).setCellValue("");
            } else {
                row.createCell(5).setCellValue(baseStockVO.getMoney());
            }
            if (baseStockVO.getBuyman() == null){
                row.createCell(6).setCellValue("");
            } else {
                row.createCell(6).setCellValue(baseStockVO.getBuyman());
            }
            if (baseStockVO.getRealprice() == null){
                row.createCell(7).setCellValue("");
            } else {
                row.createCell(7).setCellValue(String.valueOf(baseStockVO.getRealprice()));
            }
            if (baseStockVO.getRealbuycount() == null){
                row.createCell(8).setCellValue("");
            } else {
                row.createCell(8).setCellValue(baseStockVO.getRealbuycount());
            }
            if (baseStockVO.getRealcost() == null){
                row.createCell(9).setCellValue("");
            } else {
                row.createCell(9).setCellValue(String.valueOf(baseStockVO.getRealcost()));
            }
            if (baseStockVO.getDec() == null){
                row.createCell(10).setCellValue("");
            } else {
                row.createCell(10).setCellValue(baseStockVO.getDec());
            }
            if (baseStockVO.getStatus() == null){
                row.createCell(11).setCellValue("");
            } else {
                row.createCell(11).setCellValue(baseStockVO.getStatus());
            }
//            row.createCell(7).setCellValue(String.valueOf(baseStockVO.getRealprice()));
//            row.createCell(8).setCellValue(baseStockVO.getRealbuycount());
//            row.createCell(9).setCellValue(String.valueOf(baseStockVO.getRealcost()));
//            row.createCell(10).setCellValue(baseStockVO.getDec());
//            row.createCell(11).setCellValue(baseStockVO.getStatus());

            for (int i = 1; i <= list.size(); i++) {
                cellStyle.setAlignment(HorizontalAlignment.LEFT);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                if (row.getCell(i) != null) {
                    row.getCell(i).setCellStyle(cellStyle);
                }
            }
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        byte[] bytes = byteArrayOutputStream.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=buyBack.xlsx");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(bytes);
    }

}
